package com.treasure.domain.domain.entity.document;

import com.treasure.common.exception.ParameterException;
import com.treasure.common.types.FileName;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author sunhongmin
 * @date 2023/10/20 21:46
 * @description
 */
public class UploadFileEntity {
    private final MultipartFile file;
    @Getter
    private final FileName fileName;

    public UploadFileEntity(MultipartFile file) {
        if (Objects.isNull(file)) {
            throw new ParameterException("上传文件为空");
        }
        if (isImageOrVideo(file)) {
            throw new ParameterException("当前暂不支持图片/视频格式文件上传");
        }
        this.file = file;
        this.fileName = new FileName(file.getOriginalFilename());
    }

    private boolean isImageOrVideo(MultipartFile file) {
        String contentType = file.getContentType();
        if (contentType != null) {
            if (contentType.startsWith("image")) {
                // 文件是图片格式
                return true;
            } else if (contentType.startsWith("video")) {
                // 文件是视频格式
                return true;
            }
        }
        // 文件不是图片或视频格式
        return false;
    }

    public long getFileSize() {
        return file.getSize();
    }

    /**
     * 转换为本地文件
     *
     * @param subdirectory
     * @return
     * @throws IOException
     */
    public File convertToLocalFile(String subdirectory) throws IOException {
        // ./data/document
        String projectRoot = getKnowledgeFilePath(); // 获取项目根目录
        String uploadedFileName = fileName.getValue();

        String filePath = projectRoot;
        if (subdirectory != null && !subdirectory.isEmpty()) {
            filePath = Paths.get(projectRoot, subdirectory).toString();
        }

        File directory = new File(filePath);
        if (!directory.exists()) {
            directory.mkdirs(); // 递归创建目录
        }

        File localFile = new File(directory, uploadedFileName);
        file.transferTo(localFile);
        return localFile;
    }

    @NotNull
    public static String getKnowledgeFilePath() {
        return System.getProperty("user.dir") + File.separator + "data" + File.separator + "document";
    }


}
